package com.zhong.gateway.redis;

import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * redis工具类
 */
@Component
public class RedisUntil {

    @Resource
    private RedisTemplate redisTemplate;

    private static final String CACHE_KEY_SEPARATOR = ".";

    /**
     * 构建缓存key
     */
    public String buildKey(String ...strObjs){
        return String.join(CACHE_KEY_SEPARATOR, strObjs);
    }

    /**
     * key是否存在
     */
    public Boolean exist(String key){
        return redisTemplate.hasKey(key);
    }

    /**
     * 删除key
     */
    public Boolean del(String key){
        return redisTemplate.delete(key);
    }

    /**
     * 存入(不带过期时间)
     */
    public void set(String key, String value){
        redisTemplate.opsForValue().set(key,value);
    }

    /**
     * 存入(带过期时间)
     */
    public Boolean strNx(String key, String value, Long time, TimeUnit timeUnit){
        return redisTemplate.opsForValue().setIfAbsent(key,value,time,timeUnit);
    }

    /**
     * 获取string类型缓存
     */
    public String get(String key){
        return (String) redisTemplate.opsForValue().get(key);
    }


    public Boolean zAdd(String key,String value,Long score){
      return redisTemplate.opsForZSet().add(key,value,Double.parseDouble(String.valueOf(score)));
    }

    public Long countZset(String key){
        return redisTemplate.opsForZSet().size(key);
    }

    public Set<String> rangeZset(String key, long start, long end){
        return redisTemplate.opsForZSet().range(key,start,end);
    }

    public Long removeZset(String key,Object value){
        return redisTemplate.opsForZSet().remove(key,value);
    }

    public void removeZsetList(String key,Set<String> value){
        value.stream().forEach(v->redisTemplate.opsForZSet().remove(key,v) );
    }

    public Double score(String key,Object value){
        return redisTemplate.opsForZSet().score(key,value);
    }

    public Set<String> rangeByScore(String key,Long start,Long end){
        return redisTemplate.opsForZSet().reverseRange(key,start,end);
    }

    public Object addScore(String key,Object value,Double score){
        return redisTemplate.opsForZSet().incrementScore(key,value,score);
    }

    public Object rank(String key,Object value){
        return redisTemplate.opsForZSet().rank(key,value);
    }








}
